[JavaScript] 用 Jest 做單元測試


Posted by Nicolakacha on 2020-09-05

基礎方法

先安裝 node.js,再用 npm 把 Jest 安裝起來 npm install -save-dev jest

欸,等等,不知道怎麼用 npm 嗎?請看這篇

在 package.json 做好設定,代表當我們下 $ npm run test 指令時,就會運行 Jest

"scripts": {
    "test": "jest"
  },

準備好主程式檔及測試檔

主程式檔要輸出成一個 module 來提供測試,而 test.js 則引入主程式檔,匯入匯出的方法可參考 #[JavaScript] 關於模組化、匯入、匯出
fn.js // 主程式檔

const fns = {
    repeat: function repeat(str, times){
        var result = ''
        for(var i=0; i<times; i++){
            result += str
        }
        return result
    },

    add: function add(a, b){
        return a+b
    }
}

module.exports = fns

test.js // 測試檔

const = require('./fn')
test.repeat('a重複五次', () => {
        expect(fn.repeat('a', 5)).toBe('aaaaa');
    });

測試檔也可以用 describe 包成一組方便管理
describe('測試的敘述', function(){ test… })

conat fn = require('./fn.js')

describe('測試 repeat', function(){
    test('a重複五次', () => {
        expect(fn.repeat('a', 5)).toBe('aaaaa');
    });

    test('abc重複三次', () => {
        expect(fn.repeat('abc', 3)).toBe('abcabcabc');
    });

    test('空字串重複10次', () => {
        expect(fn.repeat('', 4)).toBe('');
    });  
})

describe('測試 add', function(){
    test('5+3', () => {
        expect(fn.add(5, 3)).toBe(8);
    });

    test('10+10', () => {
        expect(fn.add(10, 10)).toBe(20);
    });

    test('30+30', () => {
        expect(fn.add(30, 30)).toBe(60);
    });  
})

執行 npm run test 就看到測試結果了

JEST

在 VSCode 導入 Jest 套件:

  1. 新增一個 `jest.config.js
    module.exports = {
    };
    
  2. 在 .test 測試檔就可以直接看到測試結果

透過 Jest Snippets 減少輸入測試語法的時間

  • tb -> expect().toBe();
  • tblt -> expect().toBeLessThan();
  • tblte -> expect().toBeLessThanOrEqual();
  • test + tab  -> test('should ', () => {});

常見的條件驗證方式

matchers:

  • expect(...).toBe(...)
  • expect(fn.isNull()).toBeNull();
  • expect(fn.isUndefined()).toBeUndefined();
  • expect(fn.checkValue(0)).toBeFalsy()
  • expect(fn.checkValue(1)).toBeTruthy()

物件對比

  • expect(fn.createUser()).toEqual()
// test (passed)
test('測試 fn 是否為 小明', () => {
  expect(fn.createUser()).toEqual({
    name: '小明'
  });
});

toBe 及 toEqual 的差異

  • toBe 是使用 Object.is 作為判斷,並非使用 ===,所以在部分情況下會與 ECMAScript 有所不同。
  • toEqual 是屬於深度比對(deep equality),一一使用 Object.is 比對物件或陣列內的純值;也由於是深度比對,就如同在物件內將值一一取出重新比對,效能上會較差一些。

TDD (Test-driven Development):

測試驅動開發:先測試再開發


#Jest #Unit Test







Related Posts

redis 套件的 Property 'on' does not exist on type 'RedisClientType'

redis 套件的 Property 'on' does not exist on type 'RedisClientType'

Day 129

Day 129

 關於GitHub

關於GitHub


Comments